package com.smartao.core.init;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.Properties;

import javax.servlet.ServletContext;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.smartao.core.BaseContext;
import com.smartao.core.Environment;
import com.smartao.core.SIDManager;
import com.smartao.core.exceptions.SmartaoException;
import com.smartao.core.info.server.AppServer;
import com.smartao.core.info.server.ServerDetector;
import com.smartao.core.info.sigar.SysInfoManager;

public class ContextLoader {

	private static final Logger logger = LoggerFactory.getLogger(ContextLoader.class);

	/**
	 * 初始化BaseContext
	 * @param context
	 */
	public static void initContext(ServletContext context) {
		BaseContext.init();
		//Properties eweaverProps = new Properties();
		String rootPath = getRootPath(context) + File.separatorChar;
		BaseContext.setRootPath(rootPath);
		BaseContext.setClassPath(rootPath + Environment.CLASS_PATH);

		AppServer appServer = ServerDetector.detectServer();
		BaseContext.setAppServer(appServer);

		String MacAddress = SysInfoManager.getFirstMacAddress();
		String SID = SIDManager.generateSID(MacAddress);
		logger.info("SID:{}", SID);
		BaseContext.setSID(SID);
		String contextPath = context.getContextPath();
		BaseContext.setContextPath(contextPath);
		logger.info("ContextPath:{}", contextPath);
	}

	/**
	 * 获取根目录
	 */
	private static String getRootPath(ServletContext context) {
		String rootPath = context.getRealPath("");
		if (rootPath == null) {// resources are in a .war (JBoss, WebLogic)
			try {
				URL url = context.getResource("");
				rootPath = url.getPath();
			} catch (Exception e) {
				logger.error("Getting root path failed!", e);
			}
		}
		logger.info("RootPath:{}", rootPath);
		return rootPath;
	}

	/**
	 * 加载配置文件
	 * @return
	 */
	protected static Properties loadProperties() {
		InputStream in = null;
		Properties properties = new Properties();
		try {
			in = ContextLoader.class.getResourceAsStream("/" + Environment.APP_PROP);
			properties.load(in);
		} catch (IOException e) {
			logger.error("Load application.properties failed!" + e);
			throw new SmartaoException("Load properties failed! Exception is:" + e);
		} finally {
			try {
				if (in != null)
					in.close();
			} catch (IOException e) {
				logger.error("Close stream error:" + e);
			}
		}
		return properties;
	}
}
